package isssr.control.src;

import isssr.dao.exception.DAOException;
import isssr.dao.factory.DAOFactory;
import isssr.dao.factory.DAOFactoryType;
import isssr.dao.interfaces.UserDAO;
import isssr.entity.src.User;
import isssr.entity.src.UserContext;
import isssr.utility.src.EncryptionUtility;

import java.io.Serializable;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;


@ManagedBean(name="userAuthenticationControl")
@RequestScoped
public class UserAuthenticationControl implements Serializable {

	
	private static final String SUCCESS_URL 	= "login-success";
	private static final String FAILURE_URL 	= "login-failure";
	private static final long serialVersionUID 	= -4920920905514190679L;	
	
	
	public UserAuthenticationControl() {}
	
	
	public String login(String username, String password)
	{
		String ret_url 	= FAILURE_URL;
		User user 		= null;
		
		try {
			
			user = this.verifyUser(username, password);
			if(user != null)
			{
				this.createSession(user);
				ret_url = SUCCESS_URL;
			}
			
			else 
			{
				this.sendMessage("Error", "Username or Password wrong!", FacesMessage.SEVERITY_ERROR);
			}
		
		} catch (DAOException e) {
			this.sendMessage("Error", "Username or Password wrong!", FacesMessage.SEVERITY_ERROR);
		}
		finally
		{
			return ret_url;
		}	
	}

	
	public String logout()
	{
		FacesContext f_context 		=  FacesContext.getCurrentInstance();
		ExternalContext e_context 	= f_context.getExternalContext();
		e_context.invalidateSession();
	    
		return FAILURE_URL;
	}
	
	
	private User verifyUser(String username, String password) throws DAOException 
	{
		password 				= EncryptionUtility.getHexHashingString(password);
		DAOFactory factory 		= DAOFactory.getDAOFactory(DAOFactoryType.HIBERNATE);
		UserDAO userDao 		= factory.getUserDAO();
		User authenticatedUser 	= userDao.getByAuth(username, password);
		return authenticatedUser;
	}
		
	
	private void createSession(User u)
	{
		UserContext current_context = new UserContext();
		current_context.setUser(u);
		FacesContext f_context =  FacesContext.getCurrentInstance();
		ExternalContext e_context = f_context.getExternalContext();
		Map<String, Object> session_map = e_context.getSessionMap();
		session_map.put("userContext", current_context);
	}
	
	
	private void sendMessage(String summary, String detail, Severity severity)
	{
		FacesMessage message = new FacesMessage(summary, detail);
		message.setSeverity(severity);
		FacesContext context = FacesContext.getCurrentInstance();  
		context.addMessage(null, message);  
	}
	
	
}
